<?php
include "soar/soar.inc";

function main()
{/*{{{*/
    ob_end_clean();
    ob_implicit_flush(true);

    $boundary="ThisRandomString";
    header("Content-type:multipart/x-mixed-replace;boundary=$boundary");
    print "--$boundary\n";

    $sock=null;

    while(true)
    {
        $delay=0;
        if($sock == null)
        {
            $timeout=5;
            $sock=sock::connect('localhost:59990', $timeout);
            if($sock === false)
            {
                errlog::add("%s: connect to server fail",
                        __METHOD__);
                $sock=null;
                $line="连接chat server失败，重连中...";
                $delay=5;
            }
            else
            {
                $line="连接chat server，成功";
            }
        }
        else
        {
            $timeout=30;
            if(sock::recv($sock, $request, $timeout) == true)
            {
                $curr=0;
                $from=para::get_item($request, $curr);
                $talk=para::get_item($request, $curr);
                $line="$from: $talk";
            }
            else
            {
                socket_close($sock);
                $sock=null;
                $line="对chat server连接中断，重连中...";
                $delay=2;
            }
        }

        print <<<EOD
Content-type:text/xml;charset=utf-8

<?xml version="1.0" encoding="utf-8"?>
<push>
<line>$line</line>
</push>
--$boundary

EOD
;

        if($delay > 0) sleep($delay);
    }
    print "--$boundary--\n";
}/*}}}*/

soar::init();
main();
?>
